package cn.cars.servlet;

import cn.cars.pojo.Car;
import cn.cars.service.CarService;
import cn.cars.service.impl.CarServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/list")
public class ListPageServlet extends HttpServlet {
    private CarService service = new CarServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");

        String name = req.getParameter("name");
        String type = req.getParameter("type");

        int pageSize = 2;
        if (req.getParameter("pageSize") != null) {
            pageSize = Integer.parseInt(req.getParameter("pageSize"));
        }
        if (pageSize < 1) {
            pageSize = 1;
        }

        int count = service.count(name, type);
        int totalPage = count / pageSize;
        if (count % pageSize > 0) {
            totalPage++;
        }

        int currPage = 1;
        if (req.getParameter("currPage") != null) {
            currPage = Integer.parseInt(req.getParameter("currPage"));
        }
        if (currPage < 1) {
            currPage = 1;
        }
        if (currPage > totalPage) {
            currPage = totalPage;
        }

        int startIndex = (currPage - 1) * pageSize;
        List list = service.carListPage(name, type, startIndex, pageSize);


        req.setAttribute("list", list);
        req.setAttribute("pageSize", pageSize);
        req.setAttribute("currPage", currPage);
        req.setAttribute("totalPage", totalPage);
        req.setAttribute("count", count);

        req.getRequestDispatcher("list.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
